package com.example.medicine.controller;


import com.example.medicine.Bean.yian.*;
import com.example.medicine.Bean.zhenghou;
import com.example.medicine.Bean.zhengzhuang;

import com.example.medicine.Mapper.yian.*;
import com.example.medicine.Mapper.zhenghouMapper;
import com.example.medicine.Mapper.zhengzhuangMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping(value="/wxya")
public class WxyaController {
    private static final String UPLOADED_FOLDER =
            "E:/IDEA Projects/loadImages/";
    @Autowired
    private yian_shexiangMapper yian_shexiangMapper;
    @Autowired
    private yian_maizhenMapper yian_maizhenMapper;
    @Autowired
    private zhenghouMapper zhenghouMapper;
    @Autowired
    private zhengzhuangMapper zhengzhuangMapper;
    @Autowired
    private yian_jibingMapper yian_jibingMapper;
    @Autowired
    private yian_jianchaMapper yian_jianchaMapper;
    @Autowired
    private yian_cankaoMapper yian_cankaoMapper;
    @Autowired
    private yian_chufangMapper yian_chufangMapper;
    @Autowired
    private yianMapper yianMapper;
    @Autowired
    private yian_xiyiMapper yian_xiyiMapper;
    @Autowired
    private yian_zhengzhuangMapper yian_zhengzhuangMapper;
    @RequestMapping("/zhenghou")
    public List<zhenghou> getZhenghou(){
        return zhenghouMapper.getAll();
    }
    @RequestMapping("/zhongyiZhengzhuang")
    public List<zhengzhuang> getzhongyiZhengzhuang(){
        return zhengzhuangMapper.getZhongyao();
    }
    @GetMapping("/")
    public List<yian> getYian(){
        return yianMapper.getAll();
    }
    @PostMapping("/")
    public void insertYianMore(@RequestParam("yian") String yianJson,
                               @RequestParam("she") String sheJson,
                               @RequestParam("mai") String maiJson,
                               @RequestParam("zhenghou") String zhenghou,
                               @RequestParam("bingji") String jibing,
                               @RequestParam("zhenduan") String xiyizhenduan,
                               @RequestParam("jiancha") String jianchaJson,
                               @RequestParam(value = "fileArray",required = false) MultipartFile[] xiyifiles,
                               @RequestParam("yao") String chufangJson,
                               @RequestParam(value = "imageCover" ,required = false) MultipartFile imageCover,
                               @RequestParam(value = "imageRight" ,required = false) MultipartFile imageRight,
                               @RequestParam(value = "cankaoFiles",required = false) MultipartFile[] cankaoFiles) throws IOException {
        String coverName=null,rightName=null;
        if(imageCover!=null&&!imageCover.isEmpty()){
            coverName=fileLoad(imageCover);
        }
        if(imageRight!=null&&!imageRight.isEmpty()){
            rightName=fileLoad(imageRight);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        yian yian = objectMapper.readValue(yianJson, yian.class);
        yian.setFengmian(coverName);
        yian.setDimian(rightName);
        yianMapper.insert(yian);
        long yianId = yian.getId();
        if(!sheJson.equals("[]")) {
            loadShe(yianId, sheJson);
        }
        if(!maiJson.equals("[]")) {
            loadMai(yianId, maiJson);
        }
        if(!zhenghou.equals("null,null")) {
            yian_zhengzhuang yian_zhengzhuang = new yian_zhengzhuang();
            yian_zhengzhuang.setYianid((int) yianId);
            yian_zhengzhuang.setZhenghou(zhenghou);
            yian_zhengzhuangMapper.insertOne(yian_zhengzhuang);
        }
        if(!jibing.equals("null,null")) {
            yian_jibing yian_jibing = new yian_jibing();
            yian_jibing.setYianid(yianId);
            yian_jibing.setMingcheng(jibing);
            yian_jibing.setFenglei("中医");
            yian_jibingMapper.insertOne(yian_jibing);
        }
        if(xiyizhenduan!=null&&!xiyizhenduan.equals("")&&!xiyizhenduan.equals(" ")) {
            yian_xiyi yian_xiyi = new yian_xiyi();
            yian_xiyi.setYianid(yianId);
            yian_xiyi.setName(xiyizhenduan);
            yian_xiyiMapper.insertOne(yian_xiyi);
        }
        if(jianchaJson!=null&&!jianchaJson.equals("null")){
            loadJiancha(yianId,jianchaJson,xiyifiles);
        }
        if(chufangJson!=null&&!chufangJson.equals("[]")){
            loadYao(yianId,chufangJson);
        }
        if(cankaoFiles!=null){
            List<yian_cankao> cankaoList = new ArrayList<>();
            for(MultipartFile file:cankaoFiles){
                String name = file.getOriginalFilename();
                String image = fileLoad(file);
                yian_cankao yian_cankao = new yian_cankao();
                yian_cankao.setYianid(yianId);
                yian_cankao.setName(name);
                yian_cankao.setImage(image);
                cankaoList.add(yian_cankao);
            }
            if(!cankaoList.isEmpty()){
                yian_cankaoMapper.insertBatch(cankaoList);
            }
        }
    }
    private void loadShe(long yianId,String sheJson){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<JsonNode> jsonNodeList = objectMapper.readValue(sheJson, new TypeReference<List<JsonNode>>() {});
            List<yian_shexiang> yianShexiangList = new ArrayList<>();
            for (JsonNode jsonNode : jsonNodeList) {
                String type = jsonNode.get("type").asText();
                String value = jsonNode.get("value").asText();
                yian_shexiang yian_shexiang = new yian_shexiang();
                yian_shexiang.setYianid(yianId);
                if(type.equals("舌色")){
                    yian_shexiang.setShese(value);
                }
                else if(type.equals("舌态")){
                    yian_shexiang.setShetai(value);
                }
                else if(type.equals("舌形")){
                    yian_shexiang.setShexing(value);
                }
                else if(type.equals("苔质")){
                    yian_shexiang.setTaizhi(value);
                }
                else if(type.equals("苔色")){
                    yian_shexiang.setTaise(value);
                }
                else{
                    yian_shexiang.setName(value);
                }
                yianShexiangList.add(yian_shexiang);
            }
            yian_shexiangMapper.insertBatch(yianShexiangList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void loadMai(long yianId,String maiJson) {
        List<yian_maizhen> yianMaizhenList = new ArrayList<>();
        Pattern pattern = Pattern.compile("\"([^\"]+)\"");
        //正则表达式
        Matcher matcher = pattern.matcher(maiJson);
        while (matcher.find()) {
            String value = matcher.group(1);
            yian_maizhen yian_maizhen =new yian_maizhen();
            yian_maizhen.setName(value);
            yian_maizhen.setYianid(yianId);
            yianMaizhenList.add(yian_maizhen);
        }
        yian_maizhenMapper.insertBatch(yianMaizhenList);
    }
    private void loadJiancha(long yianId,String jianchaJson,MultipartFile[] tupian){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            int imgCount = 0;
            List<JsonNode> jsonNodeList = objectMapper.readValue(jianchaJson, new TypeReference<List<JsonNode>>() {});
            List<yian_jiancha> yianJianchaList = new ArrayList<>();
            for (JsonNode jsonNode : jsonNodeList) {
                String type = jsonNode.get("jianchaxiangmu").asText();
                String time = jsonNode.get("shijian").asText();
                String end = jsonNode.get("jieguo").asText();
                yian_jiancha yianJiancha =new yian_jiancha();
                yianJiancha.setYianid((int) yianId);
                yianJiancha.setJianchaxiangmu(type);
                if(time.equals("null")){
                    yianJiancha.setShijian(null);
                }else {

                    Date date = convertToJavaDate(time);
                    yianJiancha.setShijian(date);
                }
                if(end.equals("null")){
                    yianJiancha.setJieguo(null);
                }else {
                    yianJiancha.setJieguo(end);
                }
                if(tupian!=null&&tupian[imgCount] != null && !tupian[imgCount].isEmpty()){
                    yianJiancha.setTupian(fileLoad(tupian[imgCount]));
                }
                imgCount++;
                yianJianchaList.add(yianJiancha);
            }
            yian_jianchaMapper.insertBatch(yianJianchaList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void loadYao(long yianId,String yaoJson){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<JsonNode> jsonNodeList = objectMapper.readValue(yaoJson, new TypeReference<List<JsonNode>>() {});
            List<yian_chufang> yianChufangList =new ArrayList<>();
            int sortCnt = 0;
            for (JsonNode jsonNode : jsonNodeList) {
                String zhongyao = jsonNode.get("zhongyao").asText();
                String yaoliang = jsonNode.get("yaoliang").asText();
                String paozhi = jsonNode.get("paozhi").asText();
                String chandi = jsonNode.get("chandi").asText();
                String beizhu = jsonNode.get("beizhu").asText();
                String daiding = jsonNode.get("daiding").asText();
                yian_chufang yian_chufang =new yian_chufang();
                yian_chufang.setYianid(yianId);
                yian_chufang.setZhongyaoming(zhongyao);
                if(paozhi.equals("null")){
                    yian_chufang.setPaozhi(null);
                }
                else {
                    yian_chufang.setPaozhi(paozhi);
                }
                if(chandi.equals("null")){
                    yian_chufang.setChandi(null);
                }
                else {
                    yian_chufang.setChandi(chandi);
                }
                if(beizhu.equals("null")){
                    yian_chufang.setBeizhu(null);
                }
                else {
                    yian_chufang.setBeizhu(beizhu);
                }
                if(yaoliang.equals("null")){
                    yian_chufang.setYaoliang(null);
                }
                else {
                    yian_chufang.setYaoliang(yaoliang);
                }
                if(daiding.equals("null")){
                    yian_chufang.setDaiding(null);
                }
                else {
                    yian_chufang.setDaiding(daiding);
                }
                yian_chufang.setSort(sortCnt++);
                yianChufangList.add(yian_chufang);
            }
            yian_chufangMapper.insertBatch(yianChufangList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static Date convertToJavaDate(String input) {
        String inputFormat = "yyyy-MM-dd"; // 输入字符串的格式
        SimpleDateFormat inputFormatter = new SimpleDateFormat(inputFormat);

        try {
            Date date = inputFormatter.parse(input);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return null; // 返回 null 表示转换失败
        }
    }
    private String fileLoad(MultipartFile file) throws IOException {
        String fname = file.getOriginalFilename();    //获取原始的文件名
        //用UUID作为新文件名，扩展名不变  避免同名覆盖
        String newName = UUID.randomUUID()+ "." + fname.substring(fname.lastIndexOf(".")+1);
        File dest_file = new File( UPLOADED_FOLDER + newName );
        file.transferTo(dest_file);
        return newName;
    }
    @PostMapping("/batch/")
    public ResponseEntity<String> insertBatch(@RequestParam("file") MultipartFile file) {
        try {
            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
            }

            List<yian> yianList = new ArrayList<>();
            // 使用 Apache POI 解析 Excel 文件并提取数据
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过表头行
                    continue;
                }
                yian yian = new yian();
                for(int i=0;i<=13;++i){
                    String value=null;
                    Cell cell= row.getCell(i);
                    if(cell!=null){
                        CellType cellType=cell.getCellType();
                        value = switch (cellType) {
                            case STRING ->
                                // 处理字符串类型的单元格
                                    cell.getStringCellValue();
                            case NUMERIC ->
                                // 处理数值类型的单元格
                                    String.valueOf((int)cell.getNumericCellValue());
                            default -> null;
                        };
                    }
                    switch (i) {
                        case 0 -> yian.setXingming(value);
                        case 1 -> yian.setJiuzhenyisheng(value);
                        case 2 -> yian.setXingbie(value);
                        case 3 -> yian.setNianling(value);
                        case 4 -> yian.setJiuzhenleixin(value);
                        case 5 -> yian.setShuming(value);
                        case 6 -> yian.setZuozhe(value);
                        case 7 -> yian.setChubanshe(value);
                        case 8 -> yian.setBanci(value);
                        case 9 -> yian.setJzs(value);
                        case 10 -> yian.setJws(value);
                        case 11 -> yian.setZhushu(value);
                        case 12 -> yian.setXianbingshi(value);
                        case 13 -> yian.setXxxd(value);

                    }
                }
                yian.setBiaohao(getDate());
                yian.setShenhe("保存");
                yianList.add(yian);
            }
            // 将数据批量插入数据库
            if (!yianList.isEmpty()) {
                yianMapper.batchInsert(yianList);
                System.out.println("批量插入成功！");
            }
            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
        }
    }

    //    @PostMapping("/batch/")
//    public ResponseEntity<String> insertBatch(@RequestParam("file") MultipartFile file) {
//        try {
//            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
//            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
//                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
//            }
//
//            List<yian> yianList = new ArrayList<>();
//            // 使用 Apache POI 解析 Excel 文件并提取数据
//            Workbook workbook = WorkbookFactory.create(file.getInputStream());
//            Sheet sheet = workbook.getSheetAt(0);
//
//            for (Row row : sheet) {
//                if (row.getRowNum() == 0) { // 跳过表头行
//                    continue;
//                }
//                yian yian = new yian();
//                for(int i=0;i<=10;++i){
//                    String value=null;
//                    Cell cell= row.getCell(i);
//                    if(cell!=null){
//                        CellType cellType=cell.getCellType();
//                        value = switch (cellType) {
//                            case STRING ->
//                                // 处理字符串类型的单元格
//                                    cell.getStringCellValue();
//                            case NUMERIC ->
//                                // 处理数值类型的单元格
//                                    String.valueOf((int)cell.getNumericCellValue());
//                            default -> null;
//                        };
//                    }
//                    switch (i) {
//                        case 0 -> yian.setXingming(value);
//                        case 1 -> yian.setJiuzhenyisheng(value);
//                        case 2 -> yian.setXingbie(value);
//                        case 3 -> yian.setNianling(value);
//                        case 4 -> yian.setShuming(value);
//                        case 5 -> yian.setZuozhe(value);
//                        case 6 -> yian.setChubanshe(value);
//                        case 7 -> yian.setBanci(value);
//                        case 8 -> yian.setZhushu(value);
//                        case 9 -> yian.setXianbingshi(value);
//                        case 10 -> yian.setJiuzhenleixin(value);
//                    }
//                }
//                yian.setBiaohao(getDate());
//                yian.setShenhe("保存");
//                yianList.add(yian);
//            }
//            // 将数据批量插入数据库
//            if (!yianList.isEmpty()) {
//                yianMapper.batchInsert(yianList);
//                System.out.println("批量插入成功！");
//            }
//            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
//        } catch (Exception e) {
//            e.printStackTrace(); // 添加错误日志
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
//        }
//    }
    private String getDate(){
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String formattedDateTime = dateFormat.format(now);
        long currentTimeMillis = System.currentTimeMillis();
        int milliseconds = (int) (currentTimeMillis % 10000); // Get the last 4 digits
        String formattedMilliseconds = String.format("%04d", milliseconds);
        return formattedDateTime + formattedMilliseconds;
    }

    @PutMapping("/shenhe")
    public void shenhe(@RequestParam("id") long id,
                       @RequestParam("shenhe") String shenhe,
                       @RequestParam(value = "score",required = false) String score){
        yian yian = new yian();
        yian.setShenhe(shenhe);
        yian.setId(id);
        if(shenhe.equals("提交")){

            //人占位
            yianMapper.updateTj(yian);
        }
        else if(shenhe.equals("一审")){
            yian.setFirstcheckfenshu(score);
            //人占位
            yianMapper.updateYs(yian);
        }
        else {

            yian.setFirstcheckfenshu(score);
            //人占位
            yianMapper.updateEs(yian);
        }
    }

    @PutMapping("/")
    public void update(@RequestParam("yian") String yianJson,
                       @RequestParam("she") String sheJson,
                       @RequestParam("mai") String maiJson,
                       @RequestParam("zhenghou") String zhenghou,
                       @RequestParam("bingji") String jibing,
                       @RequestParam("zhenduan") String xiyizhenduan,
                       @RequestParam("jiancha") String jianchaJson,
                       @RequestParam(value = "fileArray",required = false) MultipartFile[] xiyifiles,
                       @RequestParam("yao") String chufangJson,
                       @RequestParam(value = "imageCover" ,required = false) MultipartFile imageCover,
                       @RequestParam(value = "imageRight" ,required = false) MultipartFile imageRight,
                       @RequestParam(value = "cankaoFiles",required = false) MultipartFile[] cankaoFiles) throws IOException {
        String coverName=null,rightName=null;
        ObjectMapper objectMapper = new ObjectMapper();
        yian yian = objectMapper.readValue(yianJson, yian.class);
        long yianId = yian.getId();
        yianMapper.update(yian);
        if(imageCover!=null&&!imageCover.isEmpty()){
            yian fengmian = new yian();
            coverName=fileLoad(imageCover);
            fengmian.setFengmian(coverName);
            fengmian.setId(yianId);
            yianMapper.updateFm(fengmian);
        }
        if(imageRight!=null&&!imageRight.isEmpty()){
            yian dimian = new yian();
            rightName=fileLoad(imageRight);
            dimian.setDimian(rightName);
            dimian.setId(yianId);
            yianMapper.updateDm(dimian);
        }
        deleteOthers(yianId);  //先删除再插入信息
        if(!sheJson.equals("[]")) {
            loadShe(yianId, sheJson);
        }
        if(!maiJson.equals("[]")) {
            loadMai(yianId, maiJson);
        }
        if(!zhenghou.equals("null,null")) {
            yian_zhengzhuang yian_zhengzhuang = new yian_zhengzhuang();
            yian_zhengzhuang.setYianid((int) yianId);
            yian_zhengzhuang.setZhenghou(zhenghou);
            yian_zhengzhuangMapper.insertOne(yian_zhengzhuang);
        }
        if(!jibing.equals("null,null")) {
            yian_jibing yian_jibing = new yian_jibing();
            yian_jibing.setYianid(yianId);
            yian_jibing.setMingcheng(jibing);
            yian_jibing.setFenglei("中医");
            yian_jibingMapper.insertOne(yian_jibing);
        }
        if(xiyizhenduan!=null&&!xiyizhenduan.equals("")&&!xiyizhenduan.equals(" ")) {
            yian_xiyi yian_xiyi = new yian_xiyi();
            yian_xiyi.setYianid(yianId);
            yian_xiyi.setName(xiyizhenduan);
            yian_xiyiMapper.insertOne(yian_xiyi);
        }
        if(jianchaJson!=null&&!jianchaJson.equals("null")){
            loadJiancha(yianId,jianchaJson,xiyifiles);
        }
        if(chufangJson!=null&&!chufangJson.equals("[]")){
            loadYao(yianId,chufangJson);
        }
        if(cankaoFiles!=null){
            List<yian_cankao> cankaoList = new ArrayList<>();
            for(MultipartFile file:cankaoFiles){
                String name = file.getOriginalFilename();
                String image = fileLoad(file);
                yian_cankao yian_cankao = new yian_cankao();
                yian_cankao.setYianid(yianId);
                yian_cankao.setName(name);
                yian_cankao.setImage(image);
                cankaoList.add(yian_cankao);
            }
            if(!cankaoList.isEmpty()){
                yian_cankaoMapper.insertBatch(cankaoList);
            }
        }
    }
    private void deleteOthers(long yianId ){  //删除除了yian表以外的表信息
        List<yian_cankao> cankaoList = yian_cankaoMapper.getByYianId(yianId);
        for(yian_cankao x : cankaoList){
            deleteFile(x.getImage());
        }
        yian_cankaoMapper.deleteByYianId(yianId);
        yian_chufangMapper.deleteByYianId(yianId);
        yian_jianchaMapper.deleteByYianId(yianId);
        yian_jibingMapper.deleteByYianId(yianId);
        yian_maizhenMapper.deleteByYianId(yianId);
        yian_shexiangMapper.deleteByYianId(yianId);
        yian_xiyiMapper.deleteByYianId(yianId);
        yian_zhengzhuangMapper.deleteByYianId(yianId);
    }
    private void deleteFile(String name){
        String path = UPLOADED_FOLDER + name;
        File imageFile = new File(path);
        // 检查文件是否存在并且是一个文件
        if (imageFile.exists() && imageFile.isFile()) {
            // 尝试删除文件
            if (imageFile.delete()) {
                System.out.println("图片文件删除成功！");
            } else {
                System.out.println("图片文件删除失败！");
            }
        } else {
            System.out.println("图片文件不存在！");
        }
    }
    @DeleteMapping("/{id}")
    public void deleteYian(@PathVariable long id){
        yianMapper.deleteById(id);
    }

}





